package com.power.sifa.info.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.ObjectUtil;
import com.huaban.analysis.jieba.JiebaSegmenter;
import com.huaban.analysis.jieba.SegToken;
import com.plf.common.domain.PageDataResponse;
import com.plf.common.domain.ResponseDTO;
import com.plf.common.file.model.FileVo;
import com.plf.common.utils.ExcelUtil;
import com.plf.common.utils.SpringHolder;
import com.plf.core.common.file.FileController;
import com.power.sifa.info.model.pageInfo.Law_docKeywordPageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.power.sifa.info.model.Law_doc;
import com.power.sifa.info.model.pageInfo.Law_docPageInfo;
import com.power.sifa.info.api.ILaw_docFeign;
import com.power.sifa.info.service.Law_docService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;



/**
 *   法律表控制器
 */

//@PowerLog
@RestController
@Slf4j
@Api(value = "Law_docController",tags={"法律表"})
public class Law_docController implements ILaw_docFeign{

    @Resource
    private Law_docService law_docService;
    
    @Override
    @ApiOperation("查询法律表分页列表")
    @SaCheckPermission("law_doc_list")
    public ResponseDTO list(Law_docPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo参数不能为空");
        Page<Law_doc> page = this.law_docService.findAll(pageInfo);
        List list = new ArrayList();
        if (!page.isEmpty()) {
            for (Law_doc law_doc : page) {
                law_doc.geneText();
                list.add(law_doc);
            }
        }
        PageDataResponse p = new PageDataResponse(list, page.getTotalElements(), page.getSize(), pageInfo.getPageNumber()<=1 ? 1 : pageInfo.getPageNumber());
        return ResponseDTO.succData(p);
    }

    @Override
    @ApiOperation("查看法律表")
    @SaCheckPermission("law_doc_view")
    public ResponseDTO view(String id) {
        Assert.notNull(id, "id不能为空");
        Law_doc law_doc  = law_docService.getById(id);
        if (law_doc != null) {
            law_doc.geneText();
        }
        return ResponseDTO.succData(law_doc);
    }

    @Override
    @ApiOperation("删除法律表")
    @SaCheckPermission("law_doc_del")
    public ResponseDTO delete(String id) {
        Assert.notNull(id, "id不能为空");
        law_docService.removeById(id);
        return ResponseDTO.succ();
    }

    @Override
    @ApiOperation("保存或修改法律表")
    @SaCheckPermission("law_doc_save")
    public ResponseDTO save(Law_doc law_doc) {
        Assert.notNull(law_doc, "law_doc不能为空");
        law_docService.saveOrUpdate(law_doc);
        return ResponseDTO.succ();
    }
    
    @Override
    @ApiOperation(value="批量删除法律表")
    @SaCheckPermission("law_doc_del")
    public ResponseDTO batchDel(String ids) {
        Assert.isTrue(StringUtils.hasText(ids), "ids不能为空");
        List<Integer> list = Arrays.asList(ids.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
        law_docService.removeByIds(list);
        return ResponseDTO.succ();
    }
    
    @Override
    @ApiOperation(value="导出excel")
    @SaCheckPermission("law_doc_list")
    public void output(HttpServletResponse response, Law_docPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo不能为空");
        String title = "法律表";
        String[] heads = {"编码","名称","法律性质","发布机关id","发布机关名称","发布日期","施行日期","有效性","失效日期","收录日期","来源途径","发布文号","附件id", "版本号","法律文书类型"};
        String[] fields = {"id","title","type","pubunitid","pubunitname","pubdate","execdate","status","losedate",
                "recorddate","source","pubcode","fileid","versions","groups"};
        Page<Law_doc> page = this.law_docService.findAll(pageInfo);
        ExcelUtil.exportXls(title, heads, fields, page.getContent(), response);
    }
            
    @Override
    @ApiOperation(value="导出excel模板")
    public void exportExcelTemplate(HttpServletResponse response) {
        String title = "法律表";
        //id自增或list从表可自行删除，需与导入项一致
        String[] heads = {"编码","名称","法律性质","发布机关id","发布机关名称","发布日期","施行日期","有效性","失效日期","收录日期","来源途径","发布文号","附件id","版本号","法律文书类型"};
        ExcelUtil.exportXls(title, heads, null, null, response);
    }
    
	@Override
	@ApiOperation(value="导入excel")
	public ResponseDTO importExcel(MultipartFile file) throws IOException {
        Assert.notNull(file, "file不能为空");
        //id自增或list从表可自行删除，需与下载的模板中导入项一致
        String[] fields = {"id","title","type","pubunitid","pubunitname","pubdate","execdate","status","losedate",
                "recorddate","source","pubcode","fileid","versions","groups"};
        List<Law_doc> list = (List<Law_doc>)ExcelUtil.Import(fields, file, Law_doc.class);
        if(!CollectionUtils.isEmpty(list)) {
            this.law_docService.saveAll(list);
        }
        return ResponseDTO.succ();
	}

    /**
     * 重写的分页查询方法
     * @param pageInfo
     * @return
     */
    @Override
    public ResponseDTO pageQuery(Law_docPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo参数不能为空");
        PageDataResponse result  = law_docService.pageQuery(pageInfo);
        return ResponseDTO.succData(result);
    }

    /**
     * 通过groups查询方法法律文书
     * @param law_docPageInfo
     * @return
     */
    @Override
    public ResponseDTO historyVersion(Law_docPageInfo law_docPageInfo) {
        Assert.notNull(law_docPageInfo, "law_docPageInfo");
        PageDataResponse result  = law_docService.historyVersion(law_docPageInfo);
        return ResponseDTO.succData(result);
    }

    /**
     * 法律表- 上传文件更新fileId字段
     * @param id 更新的数据的主键id
     * @param file 上传的文件
     * @return
     */
    @Override
    public ResponseDTO uploadLawFile(String id, MultipartFile file) {
        Assert.notNull(file, "file不能为空");
        Assert.notNull(id, "主键id不能为空");
        try {
            // 获取保存的数据，将其保存的对应的数据库里
            FileController fileController = SpringHolder.getBean(FileController.class);
            ResponseDTO<FileVo> result = fileController.minioUpload(file, null, null);
            if (ObjectUtil.isNotEmpty(result) && result.getCode() == ResponseDTO.succ().getCode()) {
                FileVo fileData = result.getData();
                if (ObjectUtil.isNotNull(fileData)) {
                    Law_doc law = law_docService.getById(id);
                    law.setFileid(fileData.getId());
                    law_docService.saveOrUpdate(law);
                    return ResponseDTO.succ();
                }
            }
        } catch (Exception e) {
            log.error("文件保存异常:{}", e.getMessage());
            return ResponseDTO.wrap(500, "文件保存异常");
        }
        return ResponseDTO.succ();
    }

    /**
     * 法律表- 关键字查询法律法规的标题
     * @param pageInfo 查询条件
     * @return
     */
    @Override
    public ResponseDTO searchDocByKeyword(Law_docKeywordPageInfo pageInfo) {
        Assert.notNull(pageInfo, "查询条件不能为空");
        // 将关键字进行分词
        JiebaSegmenter segmenter = new JiebaSegmenter();
        List<SegToken> tokens = segmenter.process(pageInfo.getKeyWord(), JiebaSegmenter.SegMode.INDEX);
        List<String> conWords = tokens.stream()
                .map(tk -> tk.word)
                .filter(t -> t != null && !t.isEmpty())
                .collect(Collectors.toCollection(LinkedList::new));
        pageInfo.setConWord(conWords);
        // 模糊查询
        PageDataResponse page = this.law_docService.searchDocByKeyword(pageInfo);
        return ResponseDTO.succData(page);
    }

    /**
     * 获取关键字分词
     * @param keyWord 关键字
     * @return
     */
    @Override
    public ResponseDTO getConWords(String keyWord) {
        Assert.notNull(keyWord, "查询关键字不能为空");
        // 将关键字进行分词
        JiebaSegmenter segmenter = new JiebaSegmenter();
        List<SegToken> tokens = segmenter.process(keyWord, JiebaSegmenter.SegMode.INDEX);
        List<String> conWords = tokens.stream()
                .map(tk -> tk.word)
                .filter(t -> t != null && !t.isEmpty())
                .collect(Collectors.toCollection(LinkedList::new));
        return ResponseDTO.succData(conWords);
    }

}
